package com.hkyl.hospital.service.impl;

import com.hkyl.hospital.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author gao
 * @date 2023/06/26 16:51:26
 */
@Service
public class LocalFileServiceImpl implements FileService {
    @Override
    public Map<String, String> upload(MultipartFile photo,String uploadpath) throws IOException {
        //生成一个唯一的文件名
        String newFileName = getFileName(photo);
        //创建文件夹
        getUploadPath(uploadpath);
        //存盘
        saveToDisk(photo, newFileName, uploadpath);
        //生成响应数据
        Map<String,String> map = getUrl(newFileName);
        return map;
    }

    @Override
    public void delete(String filePath) {
        File file=new File(filePath);
        file.delete();
    }

    private static Map<String,String> getUrl(String newFileName) {
        String url="http://localhost:7758/images/"+ newFileName;
        Map<String,String> map=new HashMap<>();
        map.put("url",url);
        map.put("filename", newFileName);
        return map;
    }

    private static void saveToDisk(MultipartFile photo, String newFileName, String uploadPath) throws IOException {
        photo.transferTo(new File(uploadPath, newFileName));
    }

    private static void getUploadPath(String uploadpath) {
        File dir=new File(uploadpath);
        if(!dir.exists()){
            dir.mkdir();
        }

    }

    private static String getFileName(MultipartFile photo) {
        String uuid = UUID.randomUUID().toString();
        //获取原始的文件名
        String originalFilename = photo.getOriginalFilename();
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String extension = originalFilename.substring(lastIndexOf);
        String newFileName=uuid+extension;
        return newFileName;
    }
}
